// pages/submit/complete.js
import {
  find
} from '../../../api/order';
const util = require('../../../utils/util.js')
import {
  find as groupFind
} from '../../../api/groupBuy'
import {find as bargainFind} from '../../../api/bargainBuy'
import css2canvas from "../../../utils/css2canvas"
import {
  createQrcode
} from '../../../api/member';
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    qrcode: '',
    cardInfo: {
      TagText: "****", //标签
      Name: '****', //姓名
      rule: '',
      rule1: '',
      avater: "", //需要https图片路径
      qrCode: "", //需要https图片路径
      price: '**',
      logo: 'http://cdnx.rzico.com/images/canvasMyLogo.png',
      coupons: '',
      marketPrice: '',
      activityPrice: ''
    },
    carvasQrCode: '',
    carvasAvater: '',
    carvasLogo: '',
    redPackShow:true,
    canvasType: false,
    order_Details: null,
    canvasHeight: 400,
    canvasH: 0,
    orderId: '',
    bargainOrder:'',
    groupOrder: '',
    bottonType: false,
    canvasBottonTitle:'保存图片至相册'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.orderFind(options.id)
    this.data.canvasH = (wx.getSystemInfoSync().windowWidth / 750).toFixed(2)

    const {
      userInfo
    } = app.globalData
    if (userInfo) {
      //怎么判断是否已经头像授权
      if (userInfo.hasOwnProperty("avatar")) {
        // this.data.cardInfo.Name = app.globalData.userInfo.nickname
        this.data.cardInfo.logo = app.globalData.userInfo.avatar
        this.setData({
          cardInfo: this.data.cardInfo
        })
      }
      if (userInfo.hasOwnProperty("nickname")) {
        this.data.cardInfo.Name = app.globalData.userInfo.nickname

        this.setData({
          cardInfo: this.data.cardInfo
        })
      }
    }
    this.data.canvasHeight = 680 * this.data.canvasH
    this.setData({
      canvasH: this.data.canvasH,
      canvasHeight: this.data.canvasHeight
    });

    this.createQrcodeClick()


  },
  onShareAppMessage: function (data) {
    if (this.data.order_Details.bargainBuyId) {
      return {
        title: this.data.order_Details.memberName+'邀请您抢红包啦',
        imageUrl: 'http://cdn.rzico.com/img/bargain.gif',
        desc: '分享页面的内容',
        path: '/pages/goods/bargain/bargain?id=' +this.data.order_Details.id+'&xuid=' + app.globalData.userInfo.id
      }
    }else if (this.data.order_Details.groupBuyId) {
      return {
        title: this.data.order_Details.memberName+'为您臻选好礼',
        imageUrl: this.data.groupOrder.thumbnail + '?x-oss-process=image/resize,m_fixed,h_400,w_500',
        desc: '分享页面的内容',
        path: '/pages/goods/product/groupDetails?id=' +this.data.order_Details.groupBuyId+'&xuid=' + app.globalData.userInfo.id
      }
    }
  
  },
  onShareTimeline: function () {
    if (this.data.order_Details.bargainBuyId) {
      return {
        title: this.data.order_Details.memberName+'邀请您抢红包啦',
        imageUrl: 'http://rzico.oss-cn-shenzhen.aliyuncs.com/img/bargain.gif' + '?x-oss-process=image/resize,m_fixed,h_400,w_500',
        desc: '分享页面的内容',
        path: '/pages/goods/bargain/bargain?id=' +this.data.order_Details.id+'&xuid=' + app.globalData.userInfo.id
      }
     
    }else if (this.data.order_Details.groupBuyId) {
      return {
        title: this.data.order_Details.memberName+'为您臻选好礼',
        imageUrl: this.data.groupOrder.thumbnail + '?x-oss-process=image/resize,m_fixed,h_400,w_500',
        desc: '分享页面的内容',
        path: '/pages/goods/product/groupDetails?id=' +
        this.data.order_Details.groupBuyId+'&xuid=' + app.globalData.userInfo.id
      }
    }
  },
  saveShareImg: function () {
    var that = this;
    if(this.data.canvasBottonTitle == '去分享到朋友圈'){
      this.cancleCanvasClick()
      return
    }
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'canvas-show',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              that.data.canvasBottonTitle = '去分享到朋友圈'
              that.setData({
                canvasBottonTitle:that.data.canvasBottonTitle
              })
              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  if (res.confirm) {}
                },
                fail: function (res) {}
              })
            },
            fail: function (res) {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      });
    }, 1000);
  },
  createQrcodeClick() {
    createQrcode().then(res => {
      this.data.qrcode = res.content
      this.setData({
        qrcode: this.data.qrcode
      })
      setTimeout(() => {
        this.createImageClick()
      }, 200)

    }).catch(error => {

    })
  },
  hiddenClick(){
    this.data.redPackShow=false
    this.setData({
      redPackShow:this.data.redPackShow
    })
  },
  orderFind: function (id) {
    var _this = this
    find(id).then(
      res => {
        console.log(res)
        if (res.type == 'success') {
          _this.data.order_Details = res.data.order
          if (_this.data.order_Details.groupBuyId) {
            groupFind(_this.data.order_Details.groupBuyId).then(response => {
              this.data.groupOrder = response.data.groupBuy
              this.data.groupOrder.point=(this.data.groupOrder.point/100).toFixed(2)
              this.data.cardInfo.TagText = response.data.groupBuy.name
              this.data.cardInfo.price = response.data.groupBuy.price
                this.data.cardInfo.rule = response.data.groupBuy.groupNum + '人拼团购' + response.data.groupBuy.orderNum + '人拼中'
                  this.data.cardInfo.rule1 = '未拼中得' + (response.data.groupBuy.point / 100).toFixed(1) + '元红包'
              //  else if (response.data.groupBuy.groupNum < 100 && response.data.groupBuy.groupNum >= 10 
              //   && response.data.groupBuy.orderNum < 10) {
              //   this.data.cardInfo.rule = response.data.groupBuy.groupNum + '人拼团购' + response.data.groupBuy.orderNum + '人拼中 '
              //   if ((response.data.groupBuy.point / 100) > 10) {
              //     this.data.cardInfo.rule1 = '未拼中得' + (response.data.groupBuy.point / 100).toFixed(1) + '元红包'
              //   }else{
              //     this.data.cardInfo.rule1 = '未拼中得' + (response.data.groupBuy.point / 100).toFixed(2) + '元红包'
              //   }
              // } else if (response.data.groupBuy.groupNum == 100 && response.data.groupBuy.orderNum < 10) {
              //   this.data.cardInfo.rule = response.data.groupBuy.groupNum + '人拼团购' + response.data.groupBuy.orderNum + '人拼中'
              //   if ((response.data.groupBuy.point / 100) > 10) {
              //     this.data.cardInfo.rule1 = '未拼中得' + (response.data.groupBuy.point / 100).toFixed(1) + '元红包  '
              //   }else{
              //     this.data.cardInfo.rule1 = '未拼中得' + (response.data.groupBuy.point / 100).toFixed(2) + '元红包  '
              //   }
              // }
              this.data.cardInfo.marketPrice = response.data.groupBuy.marketPrice
              this.setData({
                groupOrder: this.data.groupOrder,
                cardInfo: this.data.cardInfo
              })
            })
          }else if (_this.data.order_Details.bargainBuyId) {
            bargainFind(_this.data.order_Details.bargainBuyId).then(res=>{
                this.data.bargainOrder=res.data.bargainBuy
                this.data.bargainOrder.mypoint=(this.data.bargainOrder.point*0.003).toFixed(2)
                this.data.bargainOrder.youpoint=(this.data.bargainOrder.point*0.007).toFixed(2)
                
                this.setData({
                  bargainOrder:this.data.bargainOrder
                })
            })
          }
          _this.data.order_Details.amountPayable = res.data.order.amountPayable.toFixed(2)
          _this.data.orderId = res.data.order.id
          res.data.order.itemList.forEach(function (item) {
            if (item.subType == 2) {
              _this.data.bottonType = true
            }
          })

          _this.setData({
            order_Details: _this.data.order_Details,
            bottonType: _this.data.bottonType
          })
        }
      }

    ).catch(error => {
      console.log(error)
    })
  },

  indexClick() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  detailsClick() {
    wx.redirectTo({
      url: '/pages/order/jumpPage/order/details?id=' + this.data.orderId,
    })
  },
  toBargain(){
    wx.redirectTo({
      url: '/pages/goods/bargain/barginDetails?id=' + this.data.order_Details.bargainBuyId,
    })
  },
  toGroup() {
    wx.redirectTo({
      url: '/pages/goods/product/groupDetails?id=' + this.data.order_Details.groupBuyId,
    })
  },
  toInvitation() {
    this.data.canvasType = true
    wx.getImageInfo({
      src: util.proxyImage(app.APP_BASE_API, util.thumbnail(this.data.groupOrder.thumbnail, 600, 600)), //网络图片路径
      success: res => {
        this.data.carvasAvater = res.path; //图片临时本地路径
        wx.getImageInfo({
          src: util.proxyImage(app.APP_BASE_API, util.thumbnail(this.data.cardInfo.logo, 200, 200)), //网络图片路径
          success: res => {
            this.data.carvasLogo = res.path; //图片临时本地路径
            wx.getImageInfo({
              src: this.data.cardInfo.qrCode, //网络图片路径
              success: res => {
                console.log(res.path, 's2')
                this.data.carvasQrCode = res.path; //图片临时本地路径
                setTimeout(() => {
                  this.sharePosteCanvas()
                }, 1000)
                this.setData({
                  canvasType: this.data.canvasType
                })
              }
            })
          }
        })
      }
    })
  },
  // 画布海报
  sharePosteCanvas: function () {
    var _this = this
    wx.showLoading({
      title: '生成中...',
      mask: true,
    })
    var canvasShow = wx.createCanvasContext("canvas-show")
    let ctx = new css2canvas(canvasShow)
    var canvasForm = [{
        type: "roundRect",
        x: 0,
        y: 0,
        width: 550,
        height: 715,
        background: "#ffffff",
        borderWidth: 1,
        borderRadius: 0,
        clip: false
      },
      {
        type: "image",
        imgUrl: _this.data.carvasLogo,
        x: 20,
        y: 20,
        width: 60,
        height: 60,
        borderRadius: 30
      },
      {
        type: "text",
        x: 90,
        y: 20,
        color: "black",
        fontSize: 28,
        baseline: "top",
        content: _this.data.cardInfo.Name
      },

      {
        type: "text",
        x: 90,
        y: 56,
        color: "#999999",
        fontSize: 22,
        baseline: "top",
        content: "臻选好物，好友喊你来助力"
      },
      {
        type: "image",
        imgUrl: _this.data.carvasAvater,
        x: 20,
        y: 100,
        width: 398,
        height: 398
      },
      {
        type: "prefixText",
        x: 20,
        y: 545,
        color: "#FF3131",
        textAlign: "left",
        content: _this.data.cardInfo.price,
        tag: "￥",
        fontSize: 36,
        tagSize: 28
      },
      {
        type: "text",
        x: 20,
        y: 555,
        width: 320,
        content: _this.data.cardInfo.TagText,
        color: "#666666",
        fontSize: 24,
        textAlign: "left",
        overflow: "warp",
        maxLine: 1,
        lineHeight: 1
      },
      {
        type: "image",
        imgUrl: _this.data.carvasQrCode,
        x: 285,
        y: 515,
        width: 158,
        height: 158
      },
      {
        type: "tag",
        x: 20,
        y: 587,
        width: 300,
        height: 150,
        // background: '#faeef0',
        color: "#dd7f62",
        paddingTop: 5,
        paddingBottom: 5,
        // paddingLeft: 20,
        // paddingRight: 20,
        borderTopRadius: 10,
        fontSize: 24,
        content: _this.data.cardInfo.rule
      },
      {
        type: "tag",
        x: 20,
        y: 621,
        width: 300,
        height: 150,
        // background: '#faeef0',
        color: "#dd7f62",
        paddingTop: 5,
        paddingBottom: 5,
        // paddingLeft: 20,
        // paddingRight: 20,
        borderTopRightRadius: 10,
        fontSize: 24,
        content: _this.data.cardInfo.rule1
      },
    ]

    if (_this.data.cardInfo.marketPrice != '') {
      var marketPrice = {
        type: "prefixText",
        x: ctx.getWidth({
            text: "100",
            fontSize: 36,
            returnPx: false
          }) +
          74,
        y: 545,
        color: "#999999",
        textAlign: "left",
        content: _this.data.cardInfo.marketPrice,
        tag: "￥",
        fontSize: 28,
        tagSize: 20,
        isDel: true,
        delColor: "#999999"
      }
      canvasForm.push(marketPrice)
    }

    ctx
      .drawingView(canvasForm)
      .then(res => {
        console.log("绘制完成")
        wx.hideLoading();
      })

  },
  createImageClick() {
    let data = encodeURIComponent(this.data.qrcode + '?groupBuyId=' +this.data.order_Details.groupBuyId)
    this.data.cardInfo.qrCode = app.APP_BASE_API + '/zxing/createImage?data=' + data
    this.setData({
      cardInfo: this.data.cardInfo
    })
  },
  cancleCanvasClick() {
    this.data.canvasBottonTitle = '保存图片至相册'

    this.setData({
      canvasType:false,
      canvasBottonTitle:this.data.canvasBottonTitle
    })
  },
  waterClick() {
    wx.switchTab({
      url: 'pages/tabBar/water/water',
    })
  }
})